﻿using Domain.Entitys.Inv;
using Domain.IRepositorys.Inv;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace EFCore.Repositorys.Inv
{

    public class Inv_SampRepository : IInv_SampRepository
    {
        private readonly MyDbContext myDbContext;

        public Inv_SampRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }
        /// <summary>
        /// 删除抽检单
        /// </summary>
        /// <param name="Samp_id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_Qty_Delete(int Samp_id)
        {
          var query = await myDbContext.inv_samp.Where(x => x.Samp_id == Samp_id).FirstOrDefaultAsync();
            if (query == null)
            {
                throw new Exception("未找到对应的仓库抽检单");
            }
            query.Del_flag = '1';
            return await myDbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 查询抽检主表信息
        /// </summary>
        /// <param name="Samp_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<List<Inv_samp>> Inv_Qty_SelectCode(string Samp_code)
        {
           var quer=myDbContext.inv_samp.Where(x=>x.Del_flag=='0'&&x.Samp_code==Samp_code).ToListAsync();
            return quer;
        }
        /// <summary>
        /// 查询1抽检详细表信息
        /// </summary>
        /// <param name="Samp_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<Inv_prodInfo>> Inv_Qty_SelectDetail(string Samp_code)
        {
           var quer= await myDbContext.inv_samp.Where(x => x.Del_flag == '0' && x.Samp_code == Samp_code).FirstOrDefaultAsync();
            if (quer == null) {
                throw new Exception("抽检不存在");
            }
            var quer1= await myDbContext.inv_prodInfo.Where(x => x.Samp_id == quer.Samp_id).ToListAsync();

            return quer1;
        }
        /// <summary>
        /// 修改审核状态
        /// </summary>
        /// <param name="inv_samp"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<int> Inv_samp_audit_statusUpdate(Inv_samp inv_samp)
        {
           var samp=myDbContext.inv_samp.Where(x => x.Samp_code == inv_samp.Samp_code).FirstOrDefault();
            if (samp == null)
            {
                return Task.FromResult(0);
            }
            samp.Samp_audit_status = inv_samp.Samp_audit_status;
            samp.Samp_audit_by = inv_samp.Samp_audit_by;
            samp.Samp_audit_time = inv_samp.Samp_audit_time;
            samp.Samp_audit_opinion = inv_samp.Samp_audit_opinion;
            return myDbContext.SaveChangesAsync();
        }
        /// <summary>
        /// 查询抽检总数
        /// </summary>
        /// <param name="Samp_code"></param>
        /// <param name="Samp_type"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public  Task<int> Inv_Samp_selectCount(string Samp_code, string Samp_type)
        {
            var query = myDbContext.inv_samp.AsQueryable();

            query = query.Where(x => x.Del_flag == '0');

            // 条件1: 入库类型筛选（如果提供了）
            if (!string.IsNullOrEmpty(Samp_code))
            {
                query = query.Where(x => x.Samp_code == Samp_code);
            }

            // 条件2: 关键字搜索（如果提供了）
            if (!string.IsNullOrEmpty(Samp_type))
            {
                query = query.Where(x => x.Samp_type == Samp_type);

            }

            // 统计总数
            return  query.CountAsync();
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="Samp_code"></param>
        /// <param name="Samp_type"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Samp_SelectDto> Inv_Samp_selectFY(string Samp_code, string Samp_type, int currentPage, int pageSize)
        {
            // 使用 IQueryable 延迟构建查询
            IQueryable<Inv_samp> query = myDbContext.inv_samp;
                
            query = query.Where(x => x.Del_flag == '0');

            // 条件1: 根据 Samp_code 筛选
            if (!string.IsNullOrEmpty(Samp_code))
            {
                query = query.Where(x => x.Samp_code == Samp_code);
            }

            // 条件2: 根据 Samp_type 筛选
            if (!string.IsNullOrEmpty(Samp_type))
            {
                query = query.Where(x => x.Samp_type == Samp_type);
            }
            query = query.OrderByDescending(d => d.Create_time);
            var result = query
                .Skip((currentPage - 1) * pageSize)
                .Take(pageSize)
                .Select(main => new Samp_SelectDto
                {
                    Samp_type = main.Samp_type,
                    Samp_startdate = main.Samp_startdate,
                    Samp_code = main.Samp_code,
                    Samp_inspector = main.Samp_inspector,
                    Warehouse_code = main.Warehouse_code,
                    Warehouse_name = main.Warehouse_name,
                    Samp_results = main.Samp_results,
              
                    Samp_audit_status=main.Samp_audit_status,
                    Samp_audit_opinion=main.Samp_audit_opinion,
                    Samp_id=main.Samp_id,
                    Details = main.Details.Select(detail => new Samp_SelectDto.InvprodInfo
                    {
                        Samp_id = detail.Samp_id,
                        Pro_name = detail.Pro_name,
                        Pro_code = detail.Pro_code,
                        Pro_brand = detail.Pro_brand,
                        Pro_model = detail.Pro_model,
                        Unitmeas_id = detail.Unitmeas_id,
                        Samp_numder = detail.Samp_numder
                    }).ToList()
                })
                .ToList();

            return result;
        }
        /// <summary>
        ///添加盘点单
        /// </summary>
        /// <param name="inv_samp"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_Samp_Insert(Inv_samp inv_samp)
        {
             await myDbContext.inv_samp.AddRangeAsync(inv_samp);
            return await myDbContext.SaveChangesAsync();
        }
        /// <summary>
        /// 添加详情单
        /// </summary>
        /// <param name="inv_prodInfo"></param>
        /// <returns></returns>
        public async Task<int> Inv_prodInfo_Insert(List<Inv_prodInfo> inv_prodInfo)
        {
            await myDbContext.inv_prodInfo.AddRangeAsync(inv_prodInfo);
            return await myDbContext.SaveChangesAsync();
        }
        /// <summary>
        /// 根据编码查询Id
        /// </summary>
        /// <param name="Samp_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_sampt_selectId(string Samp_code)
        {
            var inv_samp=await myDbContext.inv_samp.FirstOrDefaultAsync(x => x.Samp_code == Samp_code && x.Del_flag == '0');
            if (inv_samp==null)
            {
                return 0;
            }
            return inv_samp.Samp_id;
        }
        /// <summary>
        /// 修改盘点单
        /// </summary>
        /// <param name="inv_Samp"></param>
        /// <param name="inv_prodInfo"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_Smap_Update(Inv_samp inv_Samp, List<Inv_prodInfo> inv_prodInfo)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                // 1. 更新主表信息
                var existingSamp = await myDbContext.inv_samp
                    .FirstOrDefaultAsync(s => s.Samp_id == inv_Samp.Samp_id);

                if (existingSamp == null)
                {
                    throw new Exception($"盘点单 {inv_Samp.Samp_code} 不存在");
                }

                // 更新允许修改的字段
                existingSamp.Samp_type = inv_Samp.Samp_type;
                existingSamp.Samp_startdate = inv_Samp.Samp_startdate;
                existingSamp.Samp_code = inv_Samp.Samp_code;
                existingSamp.Samp_inspector = inv_Samp.Samp_inspector;
                existingSamp.Warehouse_code = inv_Samp.Warehouse_code;
                existingSamp.Warehouse_name = inv_Samp.Warehouse_name;
                existingSamp.Samp_results = inv_Samp.Samp_results;
                existingSamp.Update_by = inv_Samp.Update_by;
                existingSamp.Update_time = inv_Samp.Update_time;
                existingSamp.Del_flag = inv_Samp.Del_flag;

                myDbContext.Update(existingSamp);
                await myDbContext.SaveChangesAsync();

                // 2. 获取现有明细
                var existingDetails = await myDbContext.inv_prodInfo
                    .Where(d => d.Samp_id == inv_Samp.Samp_id)
                    .ToListAsync();

                // 3. 识别三类记录：新增、更新、删除
                var toAdd = new List<Inv_prodInfo>();
                var toUpdate = new List<Inv_prodInfo>();
                var toDeleteIds = new List<int>();

                // 处理传入的新明细
                foreach (var newItem in inv_prodInfo)
                {
                    // 新增记录：ID为0或不在现有明细中
                    if (newItem.ProdInfo_id == 0 ||
                        !existingDetails.Any(d => d.ProdInfo_id == newItem.ProdInfo_id))
                    {
                        toAdd.Add(newItem);
                    }
                    // 更新记录：ID存在且字段有变化
                    else
                    {
                        var existingItem = existingDetails
                            .FirstOrDefault(d => d.ProdInfo_id == newItem.ProdInfo_id);

                        if (existingItem != null && IsProdInfoModified(existingItem, newItem))
                        {
                            toUpdate.Add(newItem);
                        }
                    }
                }

                // 识别需要删除的记录
                toDeleteIds = existingDetails
                    .Where(d => !inv_prodInfo.Any(e => e.ProdInfo_id == d.ProdInfo_id))
                    .Select(d => d.ProdInfo_id)
                    .ToList();

                // 4.1 删除不需要的明细
                if (toDeleteIds.Any())
                {
                    var deleteItems = existingDetails
                        .Where(d => toDeleteIds.Contains(d.ProdInfo_id))
                        .ToList();

                    myDbContext.inv_prodInfo.RemoveRange(deleteItems);
                }

                // 4.2 更新变化的明细
                foreach (var item in toUpdate)
                {
                    var existingItem = existingDetails
                        .FirstOrDefault(d => d.ProdInfo_id == item.ProdInfo_id);

                    if (existingItem != null)
                    {
                        // 更新允许修改的字段
                        existingItem.Pro_name = item.Pro_name;
                        existingItem.Pro_code = item.Pro_code;
                        existingItem.Pro_brand = item.Pro_brand;
                        existingItem.Pro_model = item.Pro_model;
                        existingItem.Unitmeas_id = item.Unitmeas_id;
                        existingItem.Samp_numder = item.Samp_numder;
                        existingItem.ProdInfo_totnum_qify = item.ProdInfo_totnum_qify;
                        existingItem.ProdInfo_totnum_uqual = item.ProdInfo_totnum_uqual;
                        existingItem.ProdInfo_Sampling_results = item.ProdInfo_Sampling_results;
                        existingItem.Warehouse_code = item.Warehouse_code;
                        existingItem.stock_entry_no = item.stock_entry_no;

                        myDbContext.Update(existingItem);
                    }
                }

                // 4.3 添加新明细
                foreach (var item in toAdd)
                {
                    item.Samp_id = inv_Samp.Samp_id;
                    await myDbContext.inv_prodInfo.AddAsync(item);
                }

                await myDbContext.SaveChangesAsync();
                await transaction.CommitAsync();

                return 1;
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();
                // 记录日志
                // logger.LogError(ex, "更新盘点单失败");
                return 0;
            }
        }

        // 辅助方法：检查盘点单明细是否被修改
        private bool IsProdInfoModified(Inv_prodInfo existing, Inv_prodInfo updated)
        {
            return existing.Pro_name != updated.Pro_name ||
                   existing.Pro_code != updated.Pro_code ||
                   existing.Pro_brand != updated.Pro_brand ||
                   existing.Pro_model != updated.Pro_model ||
                   existing.Unitmeas_id != updated.Unitmeas_id ||
                   existing.Samp_numder != updated.Samp_numder ||
                   existing.ProdInfo_totnum_qify != updated.ProdInfo_totnum_qify ||
                   existing.ProdInfo_totnum_uqual != updated.ProdInfo_totnum_uqual ||
                   existing.ProdInfo_Sampling_results != updated.ProdInfo_Sampling_results ||
                   existing.Warehouse_code != updated.Warehouse_code ||
                   existing.stock_entry_no != updated.stock_entry_no;
        }

        /// <summary>
        ///查询抽检单
        /// </summary>
        /// <param name="code"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Inv_samp> Inv_Select_SampSelect(string code, int currentPage, int pageSize)
        {
           
                var query = myDbContext.inv_samp.AsQueryable();

                // 筛选只有不合格数量的订单
                query = query.Where(s => s.Details.Any(d => d.ProdInfo_totnum_uqual > 0));


                

                // 如果提供了 code 参数，则按 code 筛选
                if (!string.IsNullOrEmpty(code))
                {
                    query = query.Where(s => s.Samp_code.Contains(code));
                }

               query = query.Where(s => s.Del_flag == '0' && s.Samp_audit_status == '1' && s.Samp_Outbound=='0');

                // 分页
                var pagedData = query
                    .Skip((currentPage - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();

                return pagedData;
            
        }
        /// <summary>
        /// 查询抽检单--总数--其他仓库单
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_Select_SmapSelect_Count(string code)
        {
            var query = myDbContext.inv_samp.AsQueryable();

            // 筛选只有不合格数量的订单
            query = query.Where(s => s.Details.Any(d => d.ProdInfo_totnum_uqual > 0));

            // 如果提供了 code 参数，则按 code 筛选 
            if (!string.IsNullOrEmpty(code))
            {
                query = query.Where(s => s.Samp_code.Contains(code));
            }

            query = query.Where(s => s.Del_flag == '0' && s.Samp_audit_status == '1' && s.Samp_Outbound == '0');

            return await query.CountAsync();
        }
        /// <summary>
        /// /查询抽检单的
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Inv_prodInfo> Inv_Select_Inv_prodInfo(string code)
        {
            // 1. 通过抽检单号(code)查询对应的抽检主表(Samp_id)
            var sample = myDbContext.inv_samp
                .Where(s => s.Samp_code == code && s.Del_flag != '1') // 排除已删除
                .Select(s => new { s.Samp_id })
                .FirstOrDefault();

            if (sample == null)
                return new List<Inv_prodInfo>(); // 未找到返回空列表

            // 2. 通过Samp_id查询不合格产品信息
            return myDbContext.inv_prodInfo
                .Where(p => p.Samp_id == sample.Samp_id &&
                            p.ProdInfo_totnum_uqual > 0) // 不合格数量>0
                .ToList();
        }
        /// <summary>
        ///其他出库单--审核完成之后--修改抽检单是否出库的状态
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_Samp_Outbound_update(int id)
        {
            // 根据其他出库单ID查询关联单号
            var othoutord = await myDbContext.inv_othoutord
                .FirstOrDefaultAsync(o => o.Othoutord_id == id);

            if (othoutord == null)
            {
                throw new Exception($"未找到ID为{id}的其他出库单");
            }
            var inv_samp=await myDbContext.inv_samp.Where(s => s.Samp_code == othoutord.othoutord_code_Associated).FirstOrDefaultAsync();
            if (inv_samp == null)
            { 
            throw new Exception($"未找到关联的抽检单{othoutord.othoutord_code_Associated}");
            }

            inv_samp.Samp_Outbound = '1';
            return await myDbContext.SaveChangesAsync();
        }
    }
}
    

